#ifndef _BSP_UART_STM32F103_H_
#define _BSP_UART_STM32F103_H_

#ifdef __cplusplus
extern "C" {
#endif

#include <BaseTypes.h>
#include "bsp_uart.h"
#include "stm32f103xe.h"
#include "stm32f1xx_ll_dma.h"

typedef struct Bsp_TUartCfgTag Bsp_TUartCfg;
struct Bsp_TUartCfgTag
{
    USART_TypeDef* uart_base;   ///< 串口基地址
    DMA_TypeDef* dma_base;      ///< DMA基地址
    UInt32 dma_tx_ch;           ///< DMA发送通道
    UInt32 dma_rx_ch;           ///< DMA接收通道
    Bool is_dma;                ///< 是否使用DMA
};

typedef struct Bsp_TUartItemTag Bsp_TUartItem;
struct Bsp_TUartItemTag
{
    void *user_data;                        ///< 用户数据
    Bsp_TUartOnSendEvent on_send;           ///< 串口发送完成事件
    Bsp_TUartOnRecvEvent on_recv;           ///< 串口存在数据事件

    const Bsp_TUartCfg *cfg;                ///< 串口配置

    Int8* tx_buf;                           ///< 发送缓冲区
    UInt32 tx_buf_size;                     ///< 发送缓冲区大小
    Int8* rx_buf;                           ///< 接收缓冲区
    UInt32 rx_buf_size;                     ///< 接收缓冲区大小
    
    Int32 baudrate;                         ///< 波特率
    Int32 parity;                           ///< 奇偶校验
    UInt32 tx_last_pos;                     ///< 发送缓冲区上次指针
    UInt32 tx_pos;                          ///< 发送缓冲区当前指针
    UInt32 rx_pos;                          ///< 接收缓冲区当前指针
    UInt32 rx_last_pos;                     ///< 接收缓冲区读指针
    Bool is_busy;                           ///< 串口忙标志

    UInt8 id;                               ///< 标识 
    Bool is_open;                           ///< 打开标志
};

typedef struct Bsp_TUartUnionTag Bsp_TUartUnion;
struct Bsp_TUartUnionTag
{
    Bsp_TUartItem* items;   ///< 串口item
    Int32 count;            ///< 串口个数
};

extern Bsp_TUartUnion g_bsp_uart_union;

void Bsp_UartInit_(void);

void Bsp_UartDone_(void);

void Bsp_UartOpen_(void);

void Bsp_UartClose_(void);

void Drv_UartOpen(Bsp_TUartItem* item);
void Drv_UartClose(Bsp_TUartItem* item);
Int32 Drv_UartRead(Bsp_TUartItem* item, void *buf, UInt32 size);
Int32 Drv_UartWrite(Bsp_TUartItem* item, const void *data, UInt32 size);
Int32 Drv_UartReadableCount(Bsp_TUartItem* item);

#ifdef __cplusplus
} // extern "C" {
#endif

#endif /* _BSP_UART_STM32F103_H_ */
